package com.hfb.mashibing.alip8.system.io;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

public class T04_NIO_SocketNIO {

    public static void main(String[] args) throws IOException {
        List<SocketChannel> clients = new LinkedList<>();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress("127.0.0.1",9090));

        ssc.configureBlocking(false); // false：非阻塞 OS NONBlocking
        ssc.setOption(StandardSocketOptions.TCP_NODELAY, false);

        while (true) {
            // 连接客户端
            SocketChannel client = ssc.accept(); // 不会阻塞，C原因返回-1，java返回null
            if (Objects.nonNull(client)) {
                System.out.println("null...");
            } else {
                client.configureBlocking(false); // 非阻塞
                int port = client.socket().getPort();
                System.out.println("client...port:" + port);
                clients.add(client);
            }

            // 接收数据，读数据
            ByteBuffer buffer = ByteBuffer.allocateDirect(4096);
            for (SocketChannel sc : clients) { // 串行化
                int  num = sc.read(buffer); // 不会阻塞
                if  (num > 0) {
                    buffer.flip();
                    byte[] a = new byte[buffer.limit()];
                    buffer.get(a);
                }
            }
            System.out.println("clients length: " + clients.size());
        }




    }

}
